package com.cloud.service.impl;

import com.joyoung.common.controller.RestRes;
import com.joyoung.common.exception.exceptions.BusinessException;
import com.cloud.feign.resp.KeyAccessoryData;
import com.cloud.feign.service.MesReportFeign;
import com.cloud.resp.AccessoryTraceSourceBaseDto;
import com.cloud.resp.AccessoryTraceSourceDto;
import com.cloud.resp.AccessoryTraceSourceTaskDto;
import com.cloud.service.AccessoryTraceSourceService;
import com.cloud.utils.BeanConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Slf4j
public class AccessoryTraceSourceServiceImpl implements AccessoryTraceSourceService {

    @Autowired
    private MesReportFeign mesExternalFeign;

    @Override
    public AccessoryTraceSourceDto queryAccessoryBySnCode(String snCode) {
        if(StringUtils.isEmpty(snCode)){
            log.error("查询配件SN码为空");
            throw new BusinessException("请输入配件SN码");
        }
        AccessoryTraceSourceDto result = new AccessoryTraceSourceDto();
        // 调用MES获取配件SN码对应信息
        RestRes<KeyAccessoryData> keyAccessoryData = mesExternalFeign.getKeyAccessory(snCode);
        KeyAccessoryData keyAccessory = keyAccessoryData.getData();
        if (keyAccessory == null || keyAccessory.getAccessoryBasicInfo() == null) {
            log.error("查询MES配件基础数据结果为空，产品码: {}", snCode);
            throw new BusinessException("此配件SN码不存在");
        }
        AccessoryTraceSourceBaseDto accessoryBaseDto =
                BeanConvertUtil.convert(keyAccessory.getAccessoryBasicInfo(), AccessoryTraceSourceBaseDto.class);
        result.setAccessoryBase(accessoryBaseDto);

        if (CollectionUtils.isEmpty(keyAccessory.getAccessoryTasks())) {
            log.info("MES系统未查询到配件溯源-关键配件相关信息,配件SN码: {}", snCode);
        } else {
            List<AccessoryTraceSourceTaskDto> accessoryTasks =
                    BeanConvertUtil.convertList(keyAccessory.getAccessoryTasks(), AccessoryTraceSourceTaskDto.class);
            result.setAccessoryTasks(accessoryTasks);
        }

        return result;
    }
}
